package com.general.framework.cc.lock;

public class T12 {
    private boolean flag = false;

    public synchronized void produce() {
        while (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生产者开始生产");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        flag = true;
        // 生产完毕通知消费者消费
        notify();
    }

    public synchronized void consume() {
        while (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消费者开始消费");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        flag = false;
        // 消费完毕通知生产者生产
        notify();
    }
    public static void main(String[] args) {
        T12 t12 = new T12();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                t12.produce();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                t12.consume();
            }
        }).start();

    }
}
